package com.cy.interfacetest.util;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.graphics.Point;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class DeviceUtil {

    private static final String TAG = "DeviceUtil";
    private static final String MOBILE_NAME_SamSung_S7 = "SM-G9300";//三星S7
    private static final String MOBILE_NAME_SamSung_NOTE4 = "SM-N9108V"; //note4
    private static final String MOBILE_NAME_HuaWei_P9 = "EVA-DL00";//华为P9
    private static final String MOBILE_NAME_HuaWei_P9_VTR = "VTR-DL00";//华为P9
    private static final String MOBILE_NAME_HuaWei_Honor8 = "FRD-AL00";  //荣耀8
    private static final String MOBILE_NAME_HuaWei_Mate9 = "MHA-AL00";  //Mate9
    private static final String MOBILE_NAME_HuaWei_Mate8 = "HUAWEI NXT-TL00";  //Mate8
    private static final String MOBILE_NAME_HuaWei_G9 = "HUAWEI VNS-AL00";  //G9
    private static final String MOBILE_NAME_OPPO_R9s = "OPPO R9s";


    private static ArrayList<String> sPhoneList = new ArrayList<String>();

    static {
        sPhoneList.add(MOBILE_NAME_SamSung_S7);
        sPhoneList.add(MOBILE_NAME_SamSung_NOTE4);
        sPhoneList.add(MOBILE_NAME_HuaWei_P9);
        sPhoneList.add(MOBILE_NAME_HuaWei_P9_VTR);
        sPhoneList.add(MOBILE_NAME_HuaWei_Mate9);
        sPhoneList.add(MOBILE_NAME_HuaWei_Mate8);
        sPhoneList.add(MOBILE_NAME_HuaWei_Honor8);
        sPhoneList.add(MOBILE_NAME_HuaWei_G9);
        sPhoneList.add(MOBILE_NAME_OPPO_R9s);
    }


    public static boolean isBuBiaoDevice() {
        boolean b = isZETDevice() || isHXDevice()
                || isTDDevice() || DeviceUtil.isMeiYaDevice() || DeviceUtil.isZXADevice() || isDCWDevice();
        return b;
    }

    public static boolean isZETDevice() {  // 中兴A41
        return "ZTE A2022H".equalsIgnoreCase(Build.MODEL) || "ZTE A2122H".equalsIgnoreCase(Build.MODEL)
                || "ZTE A2021H".equalsIgnoreCase(Build.MODEL)
                || "ZTE A2023BH".equalsIgnoreCase(Build.MODEL)   //A41 ultra pro
                || "ZTE A2023H".equalsIgnoreCase(Build.MODEL)    //A41 ultra
                || "ZTE A2023".equalsIgnoreCase(Build.MODEL)  //A41PRO
                || "ZTE A2022P".equalsIgnoreCase(Build.MODEL);   //A31 Ultra

    }

    public static boolean isMeiYaDevice() {  // 美亚
        boolean is = "DC-8630".equalsIgnoreCase(Build.MODEL);
        return is;
    }

    public static boolean isHXDevice() {  // 海信
        boolean is = "HNR553T".equalsIgnoreCase(Build.MODEL);
        return is;
    }

    public static boolean isGXXDevice() {  // 高新兴 e6  M7 同型号
        boolean is = "BSZ307".equalsIgnoreCase(Build.MODEL);
        return is;
    }

    public static boolean isM9() {  // M9执法记录仪
        boolean is = "full_k6853v1_64_6360".equalsIgnoreCase(Build.MODEL);
        return is;
    }

    public static boolean isTDDevice() {  //鼎桥设备
        boolean is = "TDT-MA01".equalsIgnoreCase(Build.MODEL) || //M40
                "AVA-PA00".equalsIgnoreCase(Build.MODEL);    //P50
        return is;
    }

    public static boolean isHNDDevice() {  // 慧能达
        boolean is = "W-500A".equalsIgnoreCase(Build.MODEL);
        return is;
    }

    public static boolean isRuixinH2Device() {  // 瑞新H2
        boolean is = "H2".equalsIgnoreCase(Build.MODEL);
        return is;
    }

    public static boolean isECDevice() {  // ES520执法记录仪
        boolean is = "EC520".equalsIgnoreCase(Build.MODEL) || "EC420".equalsIgnoreCase(Build.MODEL);
        return is;
    }

    //中信安H9  ZXA  board:dsj_h9_zxa
    public static boolean isZXADevice() {
        boolean is = "ZXA".equalsIgnoreCase(Build.BRAND);
        return is;
    }


    public static boolean isDCWDevice() {  // 达辰威电子设备
        boolean is = "DCW".equalsIgnoreCase(Build.BRAND);
        return is;
    }

    public static boolean isTianlongDevice() { //世纪天龙
        boolean is = "Tianlong".equalsIgnoreCase(Build.BRAND);
        return is;
    }


    /**
     * 星际V9H9
     *
     * @return
     */
    public static boolean isXJV9H9() {
        return Build.BOARD.contains("dsj") || Build.BOARD.contains("v1_xingji");
    }


    /**
     * S2执法仪
     *
     * @return
     */
    public static boolean isDSJS2() {
        return "dsj_tcl".equals(Build.BOARD);
    }

    public static boolean isDSJF5() {
        return "dsj_mingdu".equalsIgnoreCase(Build.BOARD);
    }

    public static boolean isDSJA8() {
        return "DSJ-ZJHA8A1".equalsIgnoreCase(Build.BOARD);
    }


    // 获取手机型号
    public static String getModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }


    // 获取CPU最大频率（单位KHZ）
    // "/system/bin/cat" 命令行
    // "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" 存储最大频率的文件的路径
    public static String getCpuMaxFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim();
    }

    /**
     * 获取国家
     */
    public static String getCountry() {
        Locale locale = Locale.getDefault();
        return locale.getCountry();
    }

    public static int getBluetoothState() {
        try {
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (mBluetoothAdapter != null) {
                return mBluetoothAdapter.isEnabled() ? 1 : 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    public static int getWifiState(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            return wifiManager.isWifiEnabled() ? 1 : 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }


    /***
     * byte转为String
     * @param bytes
     * @return
     */
    private static String bytesToString(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes) {
            buf.append(String.format("%02X:", b));
        }
        if (buf.length() > 0) {
            buf.deleteCharAt(buf.length() - 1);
        }
        return buf.toString();
    }


    /**
     * 获得内置SD卡路径
     *
     * @return
     * @author anjx
     */
    @SuppressLint("NewApi")
    public static final String getSDCardPath() {
        String sdPath = Environment.getExternalStorageDirectory().getPath();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                && (Build.VERSION.SDK_INT < 11 || !Environment.isExternalStorageEmulated())) {
            return sdPath;
        } else {
            return null;
        }
    }


    /**
     * 获取基带版本
     */
    public static String getBasebandVer() {
        Object result = null;
        try {
            Class<?> cl = Class.forName("android.os.SystemProperties");
            Object invoker = cl.newInstance();
            Method m = cl.getMethod("get", String.class, String.class);
            result = m.invoke(invoker, "gsm.version.baseband", "no nationsky_message");
        } catch (Exception e) {
        }
        if (result == null) {
            result = "";
        }
        return result.toString();
        // return android.os.Build.VERSION.INCREMENTAL;
    }


    private static final String SAMSUNG_SN_NAME = "ril.serialnumber";
    private static final String COMMON_SN_NAME = "ro.serialno";
    private static final String COMMON_SN_SNCODE = "ro.boot.sncode";


    /**
     * 电池是否在充电
     *
     * @return 0：未充电，1：在充电
     */
    public static String getBatteryState(Context context) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent battery = context.getApplicationContext().registerReceiver(null, ifilter);
        int status = battery.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
                || status == BatteryManager.BATTERY_STATUS_FULL;
        return isCharging ? "1" : "0";
    }

    /**
     * 获取系统运行时间
     */
    public static String getBootUp() {
//        InputStreamReader ir = null;
//        LineNumberReader input = null;
//        try {
//            Process proc = Runtime.getRuntime().exec("cat /proc/uptime");
//            ir = new InputStreamReader(proc.getInputStream());
//            input = new LineNumberReader(ir);
//            String str = input.readLine();
//            if (str != null) {
//                // System.out.println(str);
//                String s[] = str.split(" ");
//                if (s.length > 1)
//                    return s[0];
//            }
//        } catch (IOException e1) {
//            e1.printStackTrace();
//        } finally {
//            if (input != null)
//                try {
//                    input.close();
//                } catch (IOException e) {
//                    NsLog.e(TAG, "exception:" + e);
//                }
//            if (ir != null)
//                try {
//                    ir.close();
//                } catch (IOException e) {
//                    NsLog.e(TAG, "exception:" + e);
//                }
//        }
//        return "-1";
        return (SystemClock.elapsedRealtime() / 1000) + "";
    }

    /**
     * 取得数据漫游是否打开
     *
     * @return 1:打开，0:未打开
     */
    public static String getRoaming(Context context) {
        ContentResolver cv = context.getContentResolver();
        return android.provider.Settings.System.getString(cv, android.provider.Settings.System.DATA_ROAMING);
    }

    public static String getAllowUnkownSource(Context context) {
        ContentResolver cv = context.getContentResolver();
        return android.provider.Settings.System.getString(cv, android.provider.Settings.System.INSTALL_NON_MARKET_APPS);
    }


    private static final String getCameraPixels(Context context, Parameters parameters) {
        List<Size> sizeList = parameters.getSupportedPictureSizes();
        int pixel = 0;
        int maxPixel = 0;
        if (sizeList != null && sizeList.size() > 0) {
            for (Size size : sizeList) {
                pixel = size.height * size.width;
                if (pixel > maxPixel) {
                    maxPixel = pixel;
                }
            }

            return String.valueOf(maxPixel / 10000);
        }
        return "";
    }

    /**
     * 比较系统版本号
     *
     * @param v1
     * @param v2
     * @return 0--等；-1--小；1--大
     */
    public static int compareVersion(String v1, String v2) {
        if (v1 == null) {
            return -1;
        }

        if (v2 == null) {
            return 1;
        }

        if (v1.equals(v2)) {
            return 0;
        }

        String[] arrayStr1 = v1.split("\\.");
        String[] arrayStr2 = v2.split("\\.");

        int leng1 = arrayStr1.length;
        int leng2 = arrayStr2.length;
        int leng = (leng1 > leng2) ? leng2 : leng1;

        int result = 0;
        for (int i = 0; i < leng; i++) {
            result = Integer.valueOf(arrayStr1[i]).compareTo(Integer.valueOf(arrayStr2[i]));
            if (result != 0) {
                return result > 0 ? 1 : -1;
            }
        }

        if (leng1 > leng2) {
            result = 1;
        } else if (leng1 < leng2) {
            result = -1;
        }

        return result;
    }


    private static final String ENABLED_NOTIFICATION_LISTENERS = "enabled_notification_listeners";

    public static boolean isNotificationAccessEnabled(Context context) {
        String pkgName = context.getPackageName();
        final String flat = Settings.Secure.getString(context.getContentResolver(),
                ENABLED_NOTIFICATION_LISTENERS);
        if (!TextUtils.isEmpty(flat)) {
            final String[] names = flat.split(":");
            for (int i = 0; i < names.length; i++) {
                final ComponentName cn = ComponentName.unflattenFromString(names[i]);
                if (cn != null) {
                    if (TextUtils.equals(pkgName, cn.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean isPlatformAboveKitkat() {
        return Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT;
    }

    public static int getScreenWidth(Context context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return metrics.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return metrics.heightPixels;
    }

    public static float getDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    public static String getDeviceManufacturer() {
        return android.os.Build.MANUFACTURER;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Point getScreenSize(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getRealMetrics(displayMetrics);
        final int width = displayMetrics.widthPixels;
        final int height = displayMetrics.heightPixels;
        return new Point(width, height);
    }

    public static String getPlatformLanguage() {
        Locale locale = Locale.getDefault();
        String languageCode = locale.getLanguage();
        if (languageCode.equals("en")) {
            return "1"; // 英文1
        } else if (languageCode.equals("zh")) {
            return "31";// 中文31
        } else if (languageCode.equals("ko")) {
            return "38";// 韩语
        } else {
            return "1";
        }
    }

    // 得到手机上面所有的接入点
    public static Cursor getApns(Context context) {
        // 注意，Ophone存储apn的URI，与android不一样
        // Uri uri = Uri.parse("content://settings/data_connection");
        Uri uri = Uri.parse("content://telephony/carriers");
        Cursor c = context.getContentResolver().query(uri,
                /* new String[] { "_id", "name", "apn"} */null, "current = 1", null, null);

        // Cursor c = context.getContentResolver().query(uri,
        // null, "null", null, null);

        return c;
    }

    public static String getApnNameById(Context context, long id) {
        String name = "";
        Uri uri = Uri.parse("content://telephony/carriers");
        Cursor c = context.getContentResolver().query(uri,
                /* new String[] { "_id", "name", "apn"} */null, "_id = " + id, null, null);
        if (c != null) {
            c.moveToFirst();
            try {
                name = c.getString(c.getColumnIndex("name"));
            } catch (CursorIndexOutOfBoundsException e) {
                name = "noapn";
            }
            c.close();
        }

        return name;
    }

    // 得到手机上面当前默认使用的接入点
    public static Cursor getCurrentApn(Context context) {
        return context.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"), null, null,
                null, null);
    }

    // 得到手机上面当前默认使用的接入点
    public static long getCurrentApnId(Context context) {
        long _id = -1;
        Cursor c = context.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"), null, null,
                null, null);
        if (c != null && c.getCount() > 0) {
            c.moveToFirst();
            _id = c.getLong(c.getColumnIndex("_id"));
        }

        if (c != null) {
            c.close();
        }

        return _id;
    }

    /**
     * 获取默认的接入点名称
     *
     * @param context
     * @return
     * @author cilyce
     * @since 2011-5-13
     */
    public static String getCurrentApnName(Context context) {
        String _id = "";
        Cursor c = context.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"), null, null,
                null, null);
        if (c != null && c.getCount() > 0) {
            c.moveToFirst();
            _id = c.getString(c.getColumnIndex("apn"));
        }

        if (c != null) {
            c.close();
        }

        return _id;
    }

    // 得到当前使用的接入点的代理地址
    public static Proxy getApnProxy(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (ni.isConnected()) { // 如果有wifi连接，则选择wifi，不返回代理
            return null;
        } else {
            Cursor c = getCurrentApn(context); // 得到默认apn
            if (c.getCount() > 0) {
                c.moveToFirst();

                String proxy = c.getString(c.getColumnIndex("proxy")); // 得到代理
                String port = c.getString(c.getColumnIndex("port")); // 得到断开号
                c.close();

                if (proxy != null && !proxy.equals("")) { // 代理地址不为空
                    if (port != null && !port.equals("")) {
                        return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy, Integer.valueOf(port)));
                    } else {
                        return null;
                    }
                }
            }
            c.close();
        }
        return null;
    }

    public static boolean isDebug(Context context) {
        return 0 != (getAppFlag(context) & ApplicationInfo.FLAG_DEBUGGABLE);
    }

    private static int getAppFlag(Context context) {
        ApplicationInfo ai = context.getApplicationInfo();
        if (ai != null) {
            return ai.flags;
        }
        return 0;
    }

    public static boolean isColorOSAbove3() {
        return getDeviceBrand().equalsIgnoreCase("oppo") && Build.VERSION.SDK_INT >= 25;
    }
}
